package com.voicechat.firstmet.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.adapter.CirclePictureAdapter;
import com.voicechat.firstmet.base.BaseActivity;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.client.OssClient;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.FaintService;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.StatusBarUtils;
import com.voicechat.firstmet.utils.Utils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.activity
 * @ClassName: PublishPhoto
 * @Description: 发布秀照
 * @Author: ljp
 * @CreateDate: 2019/1/15 15:56
 * @Version: 1.0
 */
public class PublishPhotoActivity extends BaseActivity {
    @BindView(R.id.linear_back)
    LinearLayout linearBack;
    @BindView(R.id.tv_send)
    TextView tvSend;
    @BindView(R.id.et_post_title)
    EditText etPostTitle;
    @BindView(R.id.et_photo_parse)
    EditText etPhotoParse;
    @BindView(R.id.recycler_send_cover)
    RecyclerView recyclerSendCover;//封面
    @BindView(R.id.recycler_send_pictuer)
    RecyclerView recyclerSendPictuer;//照片
    //选择图片list
    private List<LocalMedia> tlist;
    private List<LocalMedia> tlistCover;
    private CirclePictureAdapter circlePictureAdapter;
    private CirclePictureAdapter circleCoverAdapter;
    private List<LocalMedia> selectList;
    private String TAG = "PublishPhotoActivity";
    private MySelfInfoBean.ObjectBean mySeleInfo;
    List<LocalMedia> list;
    @Override
    protected int setStatusBarColor() {
        return 0;
    }

    @Override
    protected boolean isSettingStatusBarText() {
        return false;
    }

    @Override
    protected int loadLayout() {
        return R.layout.activity_publish_photo;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        list = new ArrayList<>();
        ButterKnife.bind(this);
        //透明状态栏
        StatusBarUtils.Full(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        initCover();
        initView();
    }
    /**
    * @method
    * @description 选择封面
    * @date: 2019/1/15 16:19
    * @author: ljp
    * @return
    */
    private void initCover() {
        tlistCover = new ArrayList<>();
        circleCoverAdapter = new CirclePictureAdapter(context, tlistCover, R.layout.item_send_post_picture, -1);
        recyclerSendCover.setLayoutManager(new GridLayoutManager(activity,3));
        recyclerSendCover.setAdapter(circleCoverAdapter);
        circleCoverAdapter.addFooterView(R.layout.item_send_post_picture);
        circleCoverAdapter.setAddClick(new CirclePictureAdapter.OnAddClick() {
            @Override
            public void setAddItemClick(int position) {
                initPictureCover();
            }

            @Override
            public void setRemoveItemClick(int position) {
               // tlistCover.remove(position);
               // circleCoverAdapter.refreshCurrentAdapter();
            }

            @Override
            public void setSendImgBg(boolean flag) {
            }
        });
    }

    private void initView() {
        tlist = new ArrayList<>();
        circlePictureAdapter = new CirclePictureAdapter(context, tlist, R.layout.item_send_post_picture, 1);
        recyclerSendPictuer.setLayoutManager(new GridLayoutManager(activity,3));
        recyclerSendPictuer.setAdapter(circlePictureAdapter);
        circlePictureAdapter.addFooterView(R.layout.item_send_post_picture);
        circlePictureAdapter.setAddClick(new CirclePictureAdapter.OnAddClick() {
            @Override
            public void setAddItemClick(int position) {
                initPicture();
            }
            @Override
            public void setRemoveItemClick(int position) {
                tlist.remove(position);
                circlePictureAdapter.refreshCurrentAdapter();
                if(position == 0 && circleCoverAdapter.getTlist().size() >0) {
                    tlistCover.remove(position);
                    circleCoverAdapter.refreshCurrentAdapter();
                    if(tlist.size()> 0){
                        list.clear();
                        LocalMedia localMedia = tlist.get(0);
                        list.add(localMedia);
                        circleCoverAdapter.setList(list);
                        circleCoverAdapter.refreshCurrentAdapter();
                    }
                }
            }
            @Override
            public void setSendImgBg(boolean flag) {
            }
        });
        etPhotoParse.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String trim = s.toString().trim();
                if (trim.startsWith("0") && trim.length() == 1) {
                    etPhotoParse.setText("");
                    return;
                }
                //设置不能连续输入0
                if (trim.startsWith("0")
                        && trim.length() > 1) {
                    if (!trim.substring(1, 2).equals(".")) {
                        etPhotoParse.setText(trim.subSequence(0, 1));
                        etPhotoParse.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }
    /**
     * @method
     * @description 上传照片到oss
     * @date: 2018/11/18 17:08
     * @author: ljp
     * @return
     */
    private void setOssHttp(List<String> list) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OssClient.getInstance().init(context).
                            ossUploads(list, new OssClient.OnUploadFile() {
                                @Override
                                public void onUploadFileSuccess(String info) {
                                    //Log.i(TAG, "onUploadFileSuccess: -----" + info);
                                    uploadHttp(info);
                                }
                                @Override
                                public void onUploadFileFailed(String errCode) {
                                }
                            },new StringBuffer());
                } catch (ClientException e) {
                    e.printStackTrace();
                } catch (ServiceException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    /**
     * @method
     * @description 上传图片地址到服务器
     * @date: 2018/11/18 16:40
     * @author: ljp
     * @return
     */
    private void uploadHttp(String path) {
        String[] strings = Utils.spitInfo(path, ",");
        String spitCover = strings[0];
        String title = etPostTitle.getText().toString().trim();
        String parse = etPhotoParse.getText().toString().trim();
        FaintService.uploadingSharePicture(mySeleInfo.getId(),SPUtils.getEditoString(SPUtils.SP_TOKEN),
                PhoneUtils.getDeviceInfo(context),path,spitCover,title,parse).subscribe(result -> {
            Log.i(TAG, "uploadHttp: -----"+result.toString());
            if(result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS){
                Intent intent = new Intent(activity,AuditActivity.class);
                intent.putExtra("flag",0);
                startActivity(intent);
                finish();
            }else if(result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                tvSend.setEnabled(true);
                Utils.setToken(context);
            }else {
                tvSend.setEnabled(true);
                toast_MakeText(result.getMsg());
            }
        },throwable -> {
            tvSend.setEnabled(true);
            toast_MakeText(getResources().getString(R.string.net_error));
        });

    }
    /**
     * @return
     * @method
     * @description 选择封面照片
     * @date: 2018/11/18 15:08
     * @author: ljp
     */
    private void initPictureCover() {
        // 进入相册 以下是例子：用不到的api可以不写
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .maxSelectNum(1)// 最大图片选择数量 int
                .imageSpanCount(4)// 每行显示个数 int
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片 true or false
                .isCamera(true)// 是否显示拍照按钮 true or false
                .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                .compress(true)
                //.isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                //.isGif(true)// 是否显示gif图片 true or false
                .selectionMedia(tlist)// 是否传入已选图片 List<LocalMedia> list

                /*.freeStyleCropEnabled()// 裁剪框是否可拖拽 true or false
                .openClickSound()// 是否开启点击声音 true or false
                .previewEggs()// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false*/
                .cropCompressQuality(90)// 裁剪压缩质量 默认90 int*/
                .minimumCompressSize(1024)// 小于100kb的图片不压缩
                .synOrAsy(true)//同步true或异步false 压缩 默认同步
                .isDragFrame(false)// 是否可拖动裁剪框(固定)
                .forResult(PictureConfig.REQUEST_CAMERA);//结果回调onActivityResult code
    }
    /**
     * @return
     * @method
     * @description 选择照片
     * @date: 2018/11/18 15:08
     * @author: ljp
     */
    private void initPicture() {
        // 进入相册 以下是例子：用不到的api可以不写
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .maxSelectNum(9)// 最大图片选择数量 int
                .imageSpanCount(4)// 每行显示个数 int
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片 true or false
                .isCamera(true)// 是否显示拍照按钮 true or false
                .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                .compress(true)
                //.isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                //.isGif(true)// 是否显示gif图片 true or false
                .selectionMedia(tlist)// 是否传入已选图片 List<LocalMedia> list

                /*.freeStyleCropEnabled()// 裁剪框是否可拖拽 true or false
                .openClickSound()// 是否开启点击声音 true or false
                .previewEggs()// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false*/
                .cropCompressQuality(90)// 裁剪压缩质量 默认90 int*/
                .minimumCompressSize(1024)// 小于100kb的图片不压缩
                .synOrAsy(true)//同步true或异步false 压缩 默认同步
                .isDragFrame(false)// 是否可拖动裁剪框(固定)
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    circlePictureAdapter.setList(selectList);
                    circlePictureAdapter.refreshCurrentAdapter();
                    if(circleCoverAdapter.getTlist().size() == 0){
                        list.clear();
                        LocalMedia localMedia = selectList.get(0);
                        list.add(localMedia);
                        circleCoverAdapter.setList(list);
                        circleCoverAdapter.refreshCurrentAdapter();
                    }
                    break;
                case PictureConfig.REQUEST_CAMERA:
                    // 图片、视频、音频选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    circleCoverAdapter.setList(selectList);
                    circleCoverAdapter.refreshCurrentAdapter();
                    circlePictureAdapter.setList(selectList);
                    circlePictureAdapter.refreshCurrentAdapter();
                    break;
            }
        }
    }
    private void setPictureList(){
        List<LocalMedia> tlist = circlePictureAdapter.getTlist();
        List<String> list = new ArrayList<>();
        for (int i = 0;i< tlist.size();i++){
            LocalMedia localMedia = tlist.get(i);
            list.add(localMedia.getCompressPath());
        }
        setOssHttp(list);
    }
    @OnClick({R.id.linear_back, R.id.tv_send})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.linear_back:
                finish();
                break;
            case R.id.tv_send:
                publishPhoto();
                break;
        }
    }
    /**
    * @method
    * @description 发布照片
    * @date: 2019/1/15 17:09
    * @author: ljp
    * @return
    */
    private void publishPhoto() {
        String trim = etPostTitle.getText().toString().trim();
        String trim1 = etPhotoParse.getText().toString().trim();
        if (TextUtils.isEmpty(trim)) {
            toast_MakeText("请输入相册标题");
            return;
        }
        if (TextUtils.isEmpty(trim1) || Integer.parseInt(trim1) < 100) {
            toast_MakeText("请输入不低于100金币的价格");
            return;
        }
        if (circlePictureAdapter.getTlist().size()  == 0) {
            toast_MakeText("请添加照片");
            return;
        }
        tvSend.setEnabled(false);
        setPictureList();

    }
}
